import { ProtocolType } from '../core/interfaces';

export interface SQLStatement {
    type: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE';
    tables: string[];
    columns: string[];
    conditions: string[];
    limit?: number;
    offset?: number;
}

export interface DatabaseDialect {
    convertLimit(limit?: number, offset?: number): string;
    convertFunction(func: string): string;
    convertDataType(type: string): string;
}

export class SQLParser {
    static parse(sql: string): SQLStatement {
        // 简化实现，实际应使用SQL解析器库
        const stmt: SQLStatement = {
            type: 'SELECT',
            tables: [],
            columns: [],
            conditions: []
        };

        // 提取表名
        const fromMatch = sql.match(/FROM\s+([^\s,;]+)/i);
        if (fromMatch) {
            stmt.tables = [fromMatch[1]];
        }

        // 提取列
        const selectMatch = sql.match(/SELECT\s+(.+?)\s+FROM/i);
        if (selectMatch) {
            stmt.columns = selectMatch[1].split(',').map(c => c.trim());
        }

        // 提取条件
        const whereMatch = sql.match(/WHERE\s+(.+?)(?:\s+(LIMIT|ORDER|GROUP|HAVING)|;)?$/i);
        if (whereMatch) {
            stmt.conditions = [whereMatch[1]];
        }

        // 提取LIMIT
        const limitMatch = sql.match(/LIMIT\s+(\d+)(?:\s*,\s*(\d+))?/i);
        if (limitMatch) {
            stmt.limit = parseInt(limitMatch[1]);
            if (limitMatch[2]) {
                stmt.offset = parseInt(limitMatch[2]);
            }
        }

        return stmt;
    }
}

export class MySQLDialect implements DatabaseDialect {
    convertLimit(limit?: number, offset?: number): string {
        if (limit && offset) {
            return `LIMIT ${offset}, ${limit}`;
        }
        return limit ? `LIMIT ${limit}` : '';
    }

    convertFunction(func: string): string {
        // MySQL特有函数转换
        return func;
    }

    convertDataType(type: string): string {
        return type;
    }
}

export class OracleDialect implements DatabaseDialect {
    convertLimit(limit?: number, offset?: number): string {
        if (limit && offset) {
            return `OFFSET ${offset} ROWS FETCH NEXT ${limit} ROWS ONLY`;
        }
        return limit ? `FETCH FIRST ${limit} ROWS ONLY` : '';
    }

    convertFunction(func: string): string {
        // Oracle特有函数转换
        if (func === 'NOW()') {
            return 'SYSDATE';
        }
        return func;
    }

    convertDataType(type: string): string {
        if (type === 'TEXT') {
            return 'CLOB';
        }
        return type;
    }
}